package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.WxPayService;
import com.qingcheng.service.seckill.SeckillOrderService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * @Author: LDeng
 * @Date: 2020-07-07 17:07
 */

@RestController
@RequestMapping("/pay")
public class PayController {

    @Reference
    private SeckillOrderService seckillOrderService;

    @Reference
    private WxPayService wxPayService;

    @GetMapping("/createNative")
    public Map createNative(String orderId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        SeckillOrder seckillOrder= seckillOrderService.queryByUserName(username);
        if (seckillOrder != null) {
            if ("0".equals(seckillOrder.getStatus()) &&
                    "0".equals(seckillOrder.getStatus()) &&
                    username.equals(seckillOrder.getUserId())) {
                return wxPayService.createNative(seckillOrder.getId().toString(), (int)(seckillOrder.getMoney().floatValue()*100), "http://ldeng.easy.echosite.cn/wxpay/notify.do",username);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    //回调
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request) {
        System.out.println("================》回调支付成功");
        System.out.println("request对象========》"+request);
        try {
            InputStream inputStream = new FileInputStream("c:\\temp\\aa.xml");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            outputStream.close();
            String result = new String(outputStream.toByteArray(), "utf-8");

            Map<String,String> map= WXPayUtil.xmlToMap(result);
            String username="13641505900";
            System.out.println("username==========>"+username);
            seckillOrderService.updateStatus(map.get("out_trade_no"),username,map.get("transaction_id"));
            wxPayService.notifyLogic(result);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
